
// BaseUpload.install = function(Vue){
//   Vue.component(BaseUpload.name, BaseUpload)
// }

// export default BaseUpload;


import Vue from 'vue';
import BaseUploadVue from './BaseUpload.vue';

import { destroyComponent } from '@src/util/dom';
import fastCall from '@src/component/util/fastCall.ts';
import i18n from '@src/locales';

const BaseUploadComp = Vue.extend(BaseUploadVue);

/**
 * 
 * @param {*} address
 * @param {*} options 
 */
function upload(options = {}){
  
  let instance = new BaseUploadComp({
    i18n,
    propsData: {
      ...options
    }
  });
  
  return new Promise((resolve, reject) => {
    let body = document.body;
    let oldPar = document.getElementById('faster-call-BaseUploadVue');
    if(oldPar){
      body.removeChild(oldPar);
    }
    let par = document.createElement('div');
    par.className = 'hide-block';
    par.id = 'faster-call-BaseUploadVue';
    let ele = document.createElement('div');
    par.appendChild(ele);
    let pending = false;
    
    instance.$on('destroy', () => {
      setTimeout(() => destroyComponent(instance), 100);
    })
    
    instance.$on('input', event => {
      if(pending) return;
      
      this.pending = true;
      resolve({status: 0, data: event});
      setTimeout(()=>{
        body.removeChild(par);
      }, 500)
    })
    
    instance.$on('cancel', () => {
      if(pending) return;
      this.pending = true;
      resolve({status: 1, message: 'cancel'});
    })
    
    body.appendChild(par);
    instance.$mount(ele);
    instance.chooseFile();
  })
    .then(data => {
      let callback = options.callback;
      callback && typeof callback == 'function' && callback(data);
      return data;
    })
    .catch(err => console.error('err', err));
}

const BaseUpload = {
  install(Vue){
    Vue.component(BaseUploadVue.name, BaseUploadVue)
    fastCall(Vue, 'upload', { upload })
  },
  namespace: 'upload',
}

export default BaseUpload;
